﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class LoginUI : MonoBehaviour {

	public AppMgr m_AppMgr;
	public RegisterUI m_RegisterUI;

	public InputField m_Phone;
	public InputField m_Password;
	public Text m_ErrorMsg;

	public Button m_AccountBtn;
	public AccountUI m_AccountUI;

	private void Start()
	{
		if (m_AppMgr.AppData.IsFirstLogin)
		{
			gameObject.SetActive(false);
			m_AppMgr.AppData.LoginTimes += 1;
		}
		else
		{
			var phone = m_AppMgr.AppData.PhoneNumber;
			var password = m_AppMgr.AppData.Password;

			if (!string.IsNullOrEmpty(phone) && !string.IsNullOrEmpty(password) )
			{
				m_Phone.text = phone;
				m_Password.text = password;

				LoginBtn_Click();
			}
			else
			{
				m_AccountBtn.gameObject.SetActive(false);
			}
		}
	}

	private void OnEnable()
	{
		Reset();
	}

	private void Reset()
	{
		m_Phone.text = string.Empty;
		m_Password.text = string.Empty;
		m_ErrorMsg.text = string.Empty;
	}

	public void LoginBtn_Click()
	{
		if (string.IsNullOrEmpty(m_Phone.text))
		{
			m_ErrorMsg.text = "请输入手机号";
			return;
		}

		if (m_Phone.text.Length != 11)
		{
			m_ErrorMsg.text = "手机号格式不正确";
			return;
		}

		if (string.IsNullOrEmpty(m_Password.text))
		{
			m_ErrorMsg.text = "请输入密码";
			return;
		}

		if (m_Password.text.Length < 4 || m_Password.text.Length > 10)
		{
			m_ErrorMsg.text = "密码不的小于4位，不得大于10位";
			return;
		}

		StartCoroutine(Request.Login(m_Phone.text, m_Password.text, (errorCode, accountInfo) => {
			if (errorCode != ErrorCode.Success)
			{
				m_ErrorMsg.text = errorCode == ErrorCode.Fail ? "登录失败，请重试" : ErrorMsg.Instance.GetMsg(errorCode);
			}
			else
			{
				m_AppMgr.AccountInfo = accountInfo;
				m_AppMgr.AppData.LoginTimes += 1;

				if (string.IsNullOrEmpty(m_AppMgr.AppData.PhoneNumber))
				{
					m_AppMgr.AppData.PhoneNumber = m_Phone.text;
					m_AppMgr.AppData.Password = m_Password.text;
				}

				gameObject.SetActive(false);
				if (m_AccountBtn != null)
					m_AccountBtn.gameObject.SetActive(true);

			}
		}));
	}

	public void RegisterBtn_Click()
	{
		gameObject.SetActive(false);
		m_RegisterUI.gameObject.SetActive(true);
	}
}
